package com.lzh.dlykserver.config.handler;


import com.lzh.dlykserver.constant.Constants;
import com.lzh.dlykserver.entity.TUser;
import com.lzh.dlykserver.result.R;
import com.lzh.dlykserver.service.RedisService;
import com.lzh.dlykserver.util.JSONUtils;
import com.lzh.dlykserver.util.JWTUtils;
import com.lzh.dlykserver.util.ResponseUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功的处理器
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功，执行该方法，在该方法中返回json给前端
        TUser tUser = (TUser) authentication.getPrincipal();

        //1.把tUser转为json对象,放入jwt
        String userJson = JSONUtils.toJSON(tUser);
        String jwt = JWTUtils.createJWT(userJson);
        //2.写入redis
        redisService.setValue(Constants.REDIS_JWT_KEY + tUser.getId(), jwt);
        //3.设置jwt过期时间（如果选择了记住我过期时间为7天，否则为30分钟）
        String remeberMe = request.getParameter("remeberMe");
        if (Boolean.parseBoolean(remeberMe)) {
            redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(), Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        } else {
            redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(), Constants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);
        }

        //登录成功的统一结果
        R result = R.OK(jwt);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把R以json返回给前端
        ResponseUtils.write(response, resultJSON);
    }
}
